package practise.interview;

import sun.net.www.content.text.plain;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by richard on 4/27/14.
 */
public class FilterOutIpAddress {

    String ipaddress;

    public String[] getIpSection(String ipaddress) throws Exception {
        int sectionNumber = 4;
        String[] numberSection = ipaddress.split("\\.");
        if(sectionNumber != numberSection.length){
            throw new Exception("illeagal ipaddress,length:"+numberSection.length);
        }
        for(String number : numberSection){
            try{
                Integer.parseInt(number);
            }
            catch (Exception e){
                throw new Exception("illeagal ipaddress:"+number);
            }
        }
        return numberSection;
    }

    public String[] patternSpliter(String ipaddress) throws Exception {
        Pattern pattern = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$");
        Matcher matcher = pattern.matcher(ipaddress);
        if(!matcher.matches()){
            throw new Exception("illeagal " + ipaddress);

        }
        matcher = pattern.matcher(ipaddress);
        String[] matchResult= new String[4];
        while (matcher.find()){
            for(int i =1 ; i <= matcher.groupCount();i++){
                matchResult[i-1] = matcher.group(i);
            }
        }
        return matchResult;
    }

    public static void main(String[] arg) throws Exception {
        FilterOutIpAddress filterOutIpAddress = new FilterOutIpAddress();
        for(String n : filterOutIpAddress.patternSpliter("1.1.1.1")){
            System.out.println(n);
        }

        for(String n : filterOutIpAddress.getIpSection("1.1.1.1a")){
            System.out.println(n);
        }
    }

}
